package com.causelist.db;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;

import com.causelist.exception.CauseListException;

public class CauseListDAO {
	
	private JdbcTemplate jdbcTemplate;
	
	public void setDataSource(DataSource dataSource)
	{ 
		this.jdbcTemplate = new JdbcTemplate(dataSource); 
	} 
		
	public JdbcTemplate getJdbcTemplate() 
	{
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate)
	{
		this.jdbcTemplate = jdbcTemplate;
	}

	public void insertCauseDetails(final List<String[]> inputCauseList) throws CauseListException
	{
		try
		{
		getJdbcTemplate().batchUpdate("insert into cause_details (cause_id, cause_names, cause_place, cause_justicename, cause_smsflag, cause_jobid) values (?,?,?,?,?,?);", 
	    new BatchPreparedStatementSetter() { 
						private int count = 1;
						private int arrIndex = 0;
						private int listCount = 0;
						
						@Override
						public int getBatchSize() {
							return inputCauseList.size();
						} 
						
						@Override
						public void setValues(PreparedStatement ps, int i)
								throws SQLException {
							arrIndex = 0;
							count = 1;
							ps.setString(count++,((String[])inputCauseList.get(listCount))[arrIndex++]);
							ps.setString(count++,((String[])inputCauseList.get(listCount))[arrIndex++]);
							ps.setString(count++,((String[])inputCauseList.get(listCount))[arrIndex++]);
							ps.setString(count++,((String[])inputCauseList.get(listCount))[arrIndex++]);
							ps.setString(count++,"N");
							ps.setInt(count++,1);
							listCount++;
						}

						
				    });
		}catch(Exception e)
		{
			throw new CauseListException(e.getMessage());
		}
	}
	
	public List retrieveSubscribersAndFiles()
	{
		return jdbcTemplate.queryForList("select pretext_subscriber_id,pretext_content from cause_pretext");
	}

}
